<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>OneTeam Scorecard EnhancedGrid Demo</title>

<link rel="stylesheet" type="text/css" href="../theme-remote.css" />
<style type="text/css">
body {
    font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
    font-size: 11px;
}

#debugPanel pre {
    font-family: "Lucida Console", "Courier New", Courier, monospace;
}

div.container {
    border: 0px solid green;
    margin: 10px;
}
</style>

<script type="text/javascript">
var djConfig = {
    isDebug: true,
    parseOnLoad: true,
    locale: "zh",
    extraLocale: ["en"],
    baseUrl: "../lib/dojotoolkit/dojo/",
    modulePaths: {
        "demo": "../../../script/demo",
        "com": "../../../script/com"
    }
};
</script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/dojo/1.4.3/dojo/dojo.xd.js.uncompressed.js"></script>
<script type="text/javascript">
    dojo.require("dojo.data.ItemFileWriteStore");
    dojo.require("dojo.date.locale");
    dojo.require("dojo.parser");

    dojo.require("dijit.dijit"); // optimize: load dijit layer
    dojo.require("dijit.ColorPalette");
    dojo.require("dijit.Dialog");
    dojo.require("dijit.form.CheckBox");
    dojo.require("dijit.form.ComboBox");
    dojo.require("dijit.form.Button");
    dojo.require("dijit.form.DateTextBox");
    dojo.require("dijit.form.DropDownButton");
    dojo.require("dijit.form.FilteringSelect");
    dojo.require("dijit.form.NumberSpinner");
    dojo.require("dijit.form.NumberTextBox");
    dojo.require("dijit.form.RadioButton");
    dojo.require("dijit.form.SimpleTextarea");
    dojo.require("dijit.form.Textarea");
    dojo.require("dijit.form.TextBox");
    dojo.require("dijit.form.ValidationTextBox");
    dojo.require("dijit.InlineEditBox");
    dojo.require("dijit.Menu");
    dojo.require("dijit.TitlePane");
    dojo.require("dijit.TooltipDialog");

    dojo.require("dojox.data.AndOrWriteStore");
    dojo.require("dojox.html.entities");
    dojo.require("dojox.layout.FloatingPane");
    dojo.require("dojox.layout.ResizeHandle");
    dojo.require("dojox.widget.Standby");
</script>
<script type="text/javascript" src="../script/utils.js"></script>
<script type="text/javascript" src="../script/grid.js"></script>
<script type="text/javascript" src="../script/mapping.js"></script>
<script type="text/javascript" src="../script/smd/grid.js"></script>
<script type="text/javascript">
function debug(messages) {
    var msg = demo.utils._getDebugMsg.apply(null, arguments);
    console.debug(msg);

    var msgDiv = dojo.byId("debugPanelContent");
    msgDiv.innerHTML = msg;
}

function append(messages) {
    var msg = demo.utils._getDebugMsg.apply(null, arguments);

    var msgDiv = dojo.byId("debugPanelContent");
    msgDiv.innerHTML += "\n" + msg;
}

function show(id) {
    demo.utils.show(id);
}

function hide(id) {
    demo.utils.hide(id);
}
</script>
<style type="text/css">
@import "../css/rounded-button.css";
@import "../css/rounded-corners.css";

body {
    padding: 10px;
}

.gridContainer {
    display: table-cell;
    border: 1px solid #cecece;
}

.smd-cell-caption {
    background-color: #99bbee;
    color: #000000;
    font-weight: bold;
}

.smd-cell-number {
    text-align: right;
}

a:hover {
    color: #6699cc;
}
</style>
<script type="text/javascript">
///////////////////////////////////////////////////////
if (!("grid" in demo)) {
    demo.grid = {};
}

/**
 * checkboxes for select columns in grid
 */
demo.grid.checkboxes = [];

//////////////////////////////
demo.grid.buildColumnSelectorHeaderMenu = function(grid) {
    var menu = new dijit.Menu({
        id: "columnSelectorMenu"
    });

    menu.addChild(new dijit.MenuItem({
        label: "Select columns to display"
    }));
    menu.addChild(new dijit.MenuSeparator());

    var placeholderMenuItem = new dojox.widget.PlaceholderMenuItem({
        label:"GridColumns"
    });
    menu.addChild(placeholderMenuItem);

    grid.attr("headerMenu", menu);
    grid.setupHeaderMenu();

    return menu;
};

demo.grid.makeMetricMap = function() {
    var metricMap = {};

    var _addToMetricMap = function(metric) {
        var metricTitle = metric.title;
        metricMap[metricTitle] = metric;
    };

    // metric: /pmrSGDTrend?as=ct&psgso=s |&p=y5y      |&pg=%27EB3JazzNA%27 |&pr=%27EAGJazz_Family_2$0$x$$i$$iFu%27 |&geo=KRZ4_8_Americas2_US2_US13_UNITED_STATEShp
    // 2007:   /pmrSGDTrend?as=ct&psgso=s |&p=m1y-2007 |&pg=%27EB3JazzNA%27 |&pr=%27EAGJazz_Family_2$0$x$$i$$iFu%27 |&geo=KRZ4_8_Americas2_US2_US13_UNITED_STATEShp
    // 2010:   /pmrSGDTrend?as=ct&psgso=s |&p=m1y-2010 |&pg=%27EB3JazzNA%27 |&pr=%27EAGJazz_Family_2$0$x$$i$$iFu%27 |&geo=KRZ4_8_Americas2_US2_US13_UNITED_STATEShp

    //a[row] = "pmrSGDTrend?as=ct&psgso=s";
    //spreadsheet[row][col]= new ScorecardCell("@xref(col, row)");
    //spreadsheet[row][col].drillDownURLFormula = "@url2(@cat('pmrSGDTrend?as=ct&psgso=s', @cat('&p=m1y-',@xref(col, 0))),#productGroup#,#product#,#geo#)";

    // @cat:  SFunction
    // @url2: SFunction4 = url2(baseurl, &pg=scorecardParameters.get("productGroup"), &pr=product, &geo=geo)

    // Shared (FE+BE) / All
    _addToMetricMap({
        title: "Shared (FE+BE) / All"
    });
    _addToMetricMap({
        title: "Time to final solution given (SG)(in days) - shared (FE+BE) PMRs",
        mapping: "decimalLow",
        address: "pmrSGDTrend?as=ct&psgso=s"
    });
    _addToMetricMap({
        title: "Time to final solution given (SG)(in days) - all PMRs",
        mapping: "decimalLow",
        address: "pmrSGDTrend?as=ct&psgso=a"
    });
    _addToMetricMap({
        title: "Time to close (in days) - all PMRs",
        mapping: "decimalLow",
        address: "pmrSGDTrend?as=ct&psgso=a"
    });
    _addToMetricMap({
        title: "Hours per problem (HPP) - all PMRs",
        mapping: "decimalLow",
        address: "pmrHPPTrend?as=ct&phpm=thal"
    });
    _addToMetricMap({
        title: "Hours per problem (HPP) - shared (FE+BE) PMRs",
        mapping: "decimalLow",
        address: "pmrHPPTrend?as=ct&phpm=thfb"
    });
    _addToMetricMap({
        title: "PMRs received",
        mapping: "integer",
        address: "pmrOCITrend?as=ct"
    });
    _addToMetricMap({
        title: "PMRs backlog",
        mapping: "integer",
        address: "pmrOCITrend?as=ct"
    });
    _addToMetricMap({
        title: "PMRs closed",
        mapping: "integer",
        address: "pmrOCITrend?as=ct"
    });

    // Front End (FE)
    _addToMetricMap({
        title: "Front End (FE)"
    });
    _addToMetricMap({
        title: "Response time met % - priority 1",
        mapping: "percentageLow",
        address: "callResponsivenessTrend?as=ct&pesas=n&pty=1"
    });
    _addToMetricMap({
        title: "Response time met % - all priorities",
        mapping: "percentageLow",
        address: "callResponsivenessTrend?as=ct&pesas=n&pty=all"
    });
    _addToMetricMap({
        title: "FE Self sufficiency (SS) % - all PMRs",
        mapping: "percentageLow",
        address: "pmrFESelfSufficiencyTrend?as=ct"
    });
    _addToMetricMap({
        title: "FE Transfer time met % - all priorities",
        mapping: "percentageLow",
        address: "callFETransferTrend?as=ct&pty=all"
    });
    _addToMetricMap({
        title: "FE only hours per problem",
        mapping: "decimalLow",
        address: "pmrHPPTrend?as=ct&phpm=fefo"
    });
    _addToMetricMap({
        title: "FE hours per problem - FE touched PMRs",
        mapping: "decimalLow",
        address: "pmrHPPTrend?as=ct&phpm=feft"
    });
    _addToMetricMap({
        title: "FE hours per problem - shared (FE+BE) PMRs",
        mapping: "decimalLow",
        address: "pmrHPPTrend?as=ct&phpm=fefb"
    });

    // Back End (BE)
    _addToMetricMap({
        title: "Back End (BE)"
    });
    _addToMetricMap({
        title: "BE technical update time met % - priority 1",
        mapping: "percentageLow",
        address: "callBETechUpdateTrend?as=ct"
    });
    _addToMetricMap({
        title: "BE technical update time met % - all priorities",
        mapping: "percentageLow",
        address: "callBETechUpdateTrend?as=ct&pty=all"
    });
    _addToMetricMap({
        title: "BE only hours per problem",
        mapping: "decimalLow",
        address: "pmrHPPTrend?as=ct&phpm=bebo"
    });
    _addToMetricMap({
        title: "BE hours per problem - BE touched PMRs",
        mapping: "decimalLow",
        address: "pmrHPPTrend?as=ct&phpm=bebt"
    });
    _addToMetricMap({
        title: "BE hours per problem - shared (FE+BE) PMRs",
        mapping: "decimalLow",
        address: "pmrHPPTrend?as=ct&phpm=befb"
    });

    return metricMap;
};

demo.grid.makeGridRowSet = function(data, metricMap) {
    return demo.grid.getTransposedRows(data, metricMap);
};

demo.grid.getTransposedRows = function(data, metricMap) {
    var columnField = demo.grid.getTransposedColumnField(data);

    var rowsetMap = {};
    dojo.forEach(data.rowset, function(row) {
        var columnTitle = row[columnField];
        rowsetMap[columnTitle] = row;
    });

    var transposedRows = [];
    var transposedColumns = demo.grid.getTransposedColumns(data);

    var columns = dojo.filter(data.metadata.columns, function(column) {
        return column.type !== "independent-label";
    });
    dojo.forEach(columns, function(column) {
        var transposedRow = {};
        transposedRow["metric"] = column.title;
        transposedRow["type"] = column.type;
        if (metricMap[column.title] && metricMap[column.title].address) {
            transposedRow["address"] = metricMap[column.title].address;
        }

        dojo.forEach(transposedColumns, function(transposedColumn) {
            var row = rowsetMap[transposedColumn];
            transposedRow[transposedColumn] = row[column.name];
        });
        transposedRows.push(transposedRow);
    });

    return transposedRows;
};

demo.grid.getTransposedColumns = function(data) {
    var columnField = demo.grid.getTransposedColumnField(data);

    var columnTitles = [];
    dojo.forEach(data.rowset, function(row) {
        var columnTitle = row[columnField];
        columnTitles.push(columnTitle);
    });
    columnTitles.sort();

    return columnTitles;
};

demo.grid.getTransposedColumnField = function(data) {
    var columns = dojo.filter(data.metadata.columns, function(column) {
        return column.type === "independent-label";
    });
    var labelColumn = columns && columns[0];
    var field = labelColumn.name;

    return field;
};

demo.grid.makeFormatterParameters = function() {
    var parameters = [];

    parameters.push({field: "address"}); // {0}
    parameters.push({mapping: smd.scorecard.productGroupMapping}); // {1}
    parameters.push({mapping: smd.scorecard.productMapping}); // {2}
    parameters.push({mapping: smd.scorecard.geoMapping}); // {3}

    return parameters;
};

demo.grid.getMapping = function(name) {
    return demo.mappings[name] || null;
};

demo.grid.makeColumnDefs = function(data, metricMap) {
    var columnDefs = [];

    var mappings = {
        "integer" : new demo.mapping.NumberFormatMapping("integer", "n/a", "nan").mapping,
        "decimalLow": new demo.mapping.NumberFormatMapping("decimal_low", "n/a", "nan").mapping,
        "decimalMedium": new demo.mapping.NumberFormatMapping("decimal_medium", "n/a", "nan").mapping,
        "percentageLow": new demo.mapping.NumberFormatMapping("percentage_low", "n/a", "nan").mapping,
        "percentageMedium": new demo.mapping.NumberFormatMapping("percentage_medium", "n/a", "nan").mapping
    };

    var _isCaption = function(value, rowIndex) {
        var grid = this.grid;
        var store = this.grid.store;
        var item = grid.getItem(rowIndex);
        var type = store.getValue(item, "type");
        return type === "collateral";
    };

    var _showLink = function(value, rowIndex) {
        var isCaption = _isCaption.apply(this, arguments);
        return !isCaption;
    };

    var _mapping = function(value, rowIndex) {
        var grid = this.grid;
        var store = this.grid.store;
        var item = grid.getItem(rowIndex);
        var metric = store.getValue(item, "metric");
        if (metric) {
            var metricDef = metricMap[metric];
            if (metricDef) {
                var mappingName = metricDef.mapping;
                if (mappingName) {
                    var mapping = mappings[mappingName];
                    if (mapping) {
                        return mapping.apply(this, arguments);
                    }
                }
            }
        }

        return value;
    };

    // Metrics column
    var metricColumnDef = {
        title: "Metrics",
        field: "metric",
        width: "450px",
        cellClass: function(value, rowIndex) {
            var isCaption = _isCaption.apply(this, arguments);
            return isCaption ? "smd-cell-caption" : null;
        },
        showLink: _showLink,
        link: smdConfig.contextPath + "/secure/{0}&p=y5y{1}{2}{3}"
    };
    columnDefs.push(metricColumnDef);

    // each Year column
    var years = demo.grid.getTransposedColumns(data);
    dojo.forEach(years, function(year, index) {
        var columnDef = {};

        if (index === years.length - 1) {
            columnDef.title = "YTD";
        } else {
            columnDef.title = year;
        }
        columnDef.field = year;
        columnDef.mapping = _mapping;
        columnDef.cellClass = function(value, rowIndex) {
            var isCaption = _isCaption.apply(this, arguments);
            return isCaption ? "smd-cell-caption" : "smd-cell-number";
        };
        columnDef.showLink = _showLink;
        columnDef.link = smdConfig.contextPath + "/secure/{0}&p=m1y-" + year + "{1}{2}{3}";

        columnDefs.push(columnDef);
    });

    return columnDefs;
};

//////////////////////////////////////////////////

demo.grid.buildGrid = function(nodeId, data) {
    console.time("grid");
    // initialize tree grid
    var grid = dijit.byId("grid");

    if (!grid) {
        dojo.byId("title").innerHTML = data.metadata.title;
        smd.grid.formatMetadata(dojo.byId("metadata"), data.metadata.description);
        dojo.byId("footer").innerHTML = data.metadata.footer || "xxx Confidential";

        // Create metrics
        var metricMap = demo.grid.makeMetricMap();

        // rows
        var rows = demo.grid.makeGridRowSet(data, metricMap);
        console.info("rows", rows);

        // formatter parameters
        var formatterParameters = demo.grid.makeFormatterParameters();

        // column definitions for grid
        var columnDefs = demo.grid.makeColumnDefs(data, metricMap);
        console.info("columnDefs", columnDefs);

        // parameters for grid
        var params = {
            id: "grid",
            autoWidth: true,
            autoHeight: true,
            noDataMessage: "Your selections have yielded no data. Please refine them and try again.",
            canSort: function(sortInfo) {
                return false;
            }
        };

        var configuration = {
            id: params.id,
            node: params.id,
            identifier: "metric",
            label: "Metrics",
            plugins: {
                nestedSorting: false,
                dnd: false
            },
            formatterParameters: formatterParameters,
            columnDefs: columnDefs,
            params: params
        };
        var grid = smd.grid.buildGrid(rows, configuration);
    }
    console.timeEnd("grid");
};

demo.grid.onCellClick = function(e) {
    var rowIndex = e.rowIndex;
    this.onRowClick(rowIndex);
};

///////////////////////////////////////////////////////////////
var smdConfig = {
    "pageURL": "\/secure\/scorecardOneTeam",
    "settingsLevel": "all",
    "analysisMappings": "CQDB",
    "driverType": "test",
    "analysisSpecifier": "?a=xot_t&geo=KRZ4_8_Americas2_US2_US13_UNITED_STATEShp&in=y&p=y5y&pg='EB3JazzNA'&pgc=all&pr='EAGJazz_Family_2$0$x$$i$$iFu'&sl=a&v=c",
    "userDivisionMoniker": "A2$$$e_TU",
    "userid": "Test",
    "fromYear": "2009",
    "dataTitle": "",
    "userMoniker": "A0$$$emdV",
    "contextPath": "http:\/\/9.123.233.103:9080\/dashboard",
    "analysisType": "trend",
    "year": "cur"
};

smd.scorecard = {};
smd.scorecard.params = {};

smd.scorecard._urlParamMapping = function(key) {
    var mappedValue = "";

    if (!(key in smd.scorecard.params)) {
        smd.scorecard.params[key] = demo.utils.getParameterFromUrl(key, smdConfig.analysisSpecifier);
    }

    var param = smd.scorecard.params[key];
    if (param) {
        mappedValue = "&" + key + "=" + param;
    }

    return mappedValue;
};

smd.scorecard.productGroupMapping = function(value, rowIndex) {
    var key = "pg";
    var mappedValue = smd.scorecard._urlParamMapping(key);
    return mappedValue;
};

smd.scorecard.productMapping = function(value, rowIndex) {
    var key = "pr";
    var mappedValue = smd.scorecard._urlParamMapping(key);
    return mappedValue;
};

smd.scorecard.geoMapping = function(value, rowIndex) {
    var key = "geo";
    var mappedValue = smd.scorecard._urlParamMapping(key);
    return mappedValue;
};

demo.utils.getParameterFromUrl = function(key, url) {
    var param = null;

    var pattern = "[?&]" + key + "=([^&]+)";
    var results = url.match(pattern);

    if (dojo.isArray(results) && results.length === 2) {
        param = results[1];
    }

    return param;
};

//////////////////////////////
dojo.addOnLoad(function() {
    debug("loading");

    var url = "../data/grid/xot_t-json.json";
    dojo.xhrGet({
        url: url,
        handleAs: "json",
        load: function(response, ioargs) {
            debug("loaded");
            demo.grid.buildGrid("grid", response);
        },
        error: function(error) {
            debug(error);
        }
    });
});

//////////////////////////////
// showColumnSelectorDialogButton
function showColumnSelectorDialog() {
    var grid = dijit.byId("grid");
    demo.grid.buildColumnSelectorContainer(grid, "columnSelectorContainer", 10);
    dijit.byId("gridColumnsDialog").show();
}

// showColumnsButton
function showColumns() {
    var grid = dijit.byId("grid");

    demo.grid.showSelectedColumns(grid, updateFieldSelector);
    dijit.byId("gridColumnsDialog").hide();
}

function showColumns() {
    var grid = dijit.byId("grid");

    demo.grid.showSelectedColumns(grid, updateFieldSelector);
    dijit.byId("gridColumnsDialog").hide();
}

function removeSelectedRows() {
    var grid = dijit.byId("grid");
    grid.removeSelectedRows();
}
</script>
</head>
<body class="tundra">

  <div id="main" class="container">

    <div id="titlePanel" dojoType="dijit.TitlePane" title="Panel" style="">
      <div id="resizablePanel" style="position:relative; padding: 10px; border:1px solid black;">

        <!-- Content -->
        <div class="content">
            <div class="gridContainer">
                <div id="title" style="font-weight: bold;"></div>
                <div id="gridToolbarContainer"></div>
                <!-- grid -->
                <div id="grid"></div>
                <div id="metadata"></div>
                <div id="footer" style="text-align: center; font-weight: bold; font-size: smaller; color: #880000;"></div>
            </div>
        </div>

        <!-- Resize Handle -->
        <div id="resizeHandle" dojoType="dojox.layout.ResizeHandle" targetId="resizablePanel"></div>
      </div>
    </div>

    <!-- Button Panel -->
    <div dojoType="dojo.dnd.Moveable">
      <div id="buttonPanel" dojoType="dijit.TitlePane" title="Button Panel" style="">
        <!-- Show "Select columns to display" dialog -->
        <button dojoType="dijit.form.Button" iconClass="dijitEditorIcon dijitEditorIconFullScreen" title="Show columns dialog" onClick="showColumnSelectorDialog();">Select columns</button>

        <!-- Drop Down Button -->
        <button dojoType="dijit.form.DropDownButton" iconClass="noteIcon" title="Select columns" value="Select columns" menu="">
          <span>Select columns</span>
          <!-- Header Menu -->
          <div dojoType="dijit.Menu" id="headerMenu" style="display: none;">
            <div dojoType="dojox.widget.PlaceholderMenuItem" label="GridColumns"></div>
          </div>
        </button>

        <!-- Restore columns -->
        <button dojoType="dijit.form.Button" title="Restore columns" onClick="restoreColumns();">Restore</button>

        <!-- Remove selected rows -->
        <button dojoType="dijit.form.Button" title="Remove selected row(s)" onClick="removeSelectedRows();">Remove</button>

      </div>
    </div>
  </div>

  <!-- Debug Panel -->
  <div id="debugPanel" dojoType="dojox.layout.FloatingPane" title="Console" resizable="true" dockable="true" style="position: absolute; bottom: 20px; right: 20px; width: 500px; height: 150px;">
    <pre id="debugPanelContent"></pre>
  </div>

  <!-- Show Columns Dialog -->
  <div dojoType="dijit.Dialog" id="gridColumnsDialog" title="Select Columns" style="display: none;">
    <div id="columnSelectorContainer"></div>
    <div style="clear: both;" class="hrule-dots">&nbsp;</div>
    <div id="showColumnsButton" dojoType="dijit.form.Button" onClick="showColumns();">Show columns</div>
    <div id="cancelSelectColumnsButton" dojoType="dijit.form.Button" onClick="dijit.byId('gridColumnsDialog').hide();">Cancel</div>
  </div>
</body>
</html>
